package com.xb.xbpm.controller;

import com.github.pagehelper.Page;
import com.xb.xbpm.bean.Site;
import com.xb.xbpm.service.ISiteService;
import com.xb.xbpm.utils.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 域名管理
 * @Author gxd
 * @Date： 2018/7/23
 */
@Controller
@RequestMapping(value = "site")
public class SiteController {

    @Autowired
    ISiteService siteService;

    /**
     * 获取网站列表
     */
    @RequestMapping(value = "/getSiteListByPage")
    public @ResponseBody
    Map<String, Object> getSiteListByPage(HttpServletRequest request, HttpServletResponse res) {
        ModelMap map = new ModelMap();
        String userid=request.getParameter("userid");
        String siteindex=request.getParameter("siteindex");

        int pageNum= Integer.parseInt(request.getParameter("pageNum"));
        int pageSize=Integer.parseInt(request.getParameter("pageSize"));
        Page<Site> page =siteService.getListByPage(userid,siteindex, pageNum, pageSize);
        map.put("number", page.getTotal());
        map.put("pagesdata", page);
        return map;
    }


    /**
     * 获取网站列表
     * id
     * name
     * url
     */
    @RequestMapping(value = "/getSiteList")
    public @ResponseBody
    Map<String, Object> getSiteList(HttpServletRequest request, HttpServletResponse res) {
        ModelMap map = new ModelMap();
        String userid=request.getParameter("userid");
        List<Map<String,Object>> list= new ArrayList<Map<String,Object>>();
        list=siteService.getSiteList(userid);
        map.put("list", list);
        return map;
    }


    /**
     * 保存站点信息
     */
    @RequestMapping("/saveSite")
    public @ResponseBody
    Map<String, Object> saveSite(HttpServletRequest request) {
        ModelMap map = new ModelMap();
        Integer r=0;
        String userid=request.getParameter("userid");
        String siteid=request.getParameter("siteid");
        String sitename=request.getParameter("sitename");
        String sitehome=request.getParameter("sitehome");
        String sitetype=request.getParameter("sitetype");
        String sitesummary=request.getParameter("sitesummary");

        Site site =new Site();

        if(Tools.notEmpty(siteid)){
            site.setId(siteid);
        }
        site.setUserid(userid);
        site.setSiteName(sitename);
        site.setSiteHome(sitehome);
        site.setSiteType(sitetype);
        if(Tools.notEmpty(sitesummary)){
            site.setSiteSummary(sitesummary);
        }

        try {
            r=siteService.saveSite(site);
        } catch (Exception e) {

        }
        map.put("result",r);
        return map;
    }


    /**
     * 获取站点信息bysiteId
     */
    @RequestMapping("/getSiteInfo")
    public @ResponseBody
    Map<String, Object> getSiteInfo(HttpServletRequest request) {
        ModelMap map = new ModelMap();
        Integer r=0;

        String userid=request.getParameter("userid");
        String siteid=request.getParameter("siteid");

        Site site =null;
        try {
            site= siteService.getSiteInfo(siteid);
        } catch (Exception e) {

        }
        map.put("site",site);
        return map;
    }

    /**
     * 删除站点
     */
    @RequestMapping("/delSite")
    public @ResponseBody
    Map<String, Object> delSite(HttpServletRequest request) {
        ModelMap map = new ModelMap();
        Integer r=0;
        String siteid=request.getParameter("siteid");
        try {
            r= siteService.delSiteInfo(siteid);
        } catch (Exception e) {

        }
        map.put("result",r);
        return map;
    }

    /**
     * 修改站点siteHome
     * 暂不用
     */
    @RequestMapping("/editSite")
    public @ResponseBody
    Map<String, Object> editSite(HttpServletRequest request) {
        ModelMap map = new ModelMap();
        Integer r=0;
        String userid=request.getParameter("userid");
        String siteid=request.getParameter("siteid");
        String sitehome=request.getParameter("sitehome");
        Site site =new Site();
        site.setId(siteid);
        site.setSiteHome(sitehome);
        try {
            r=siteService.editSite(site);
        } catch (Exception e) {
        }
        map.put("result",r);
        return map;
    }



    /**
     * 获取js
     */
    @RequestMapping(value = "getCode/{userid}/{siteid}")
    public void getCode(@PathVariable String userid,@PathVariable String siteid, HttpServletRequest request, HttpServletResponse res) {
        res.setContentType("text/javascript");
        PrintWriter out = null;
        try {
            out = res.getWriter();
            out.print("(function(){var win=window,doc=document;var lm_id=\""+userid+"\",site_id=\""+siteid+"\";var cookie={addCookie:function(objName,objValue,objDays){var str=objName+\"=\"+escape(objValue);if(objDays>0){var date=new Date();var ms=objDays*24*3600*1000;date.setTime(date.getTime()+ms);str+=\"; expires=\"+date.toGMTString()}if(objDays===Infinity){str+=\"; expires=Fri, 31 Dec 9999 23:59:59 GMT\"}str+=\"; path=/\";doc.cookie=str},get:function(name){var cname=name+'=';var arrCookie=doc.cookie.split(';');for(var i=0;i<arrCookie.length;i++){var cookie=arrCookie[i];while(cookie.charAt(0)==' ')cookie=cookie.substring(1);if(cookie.indexOf(name)!=-1)return cookie.substring(cname.length,cookie.length)}return''}};");
            out.print(" var arandDiv=Math.floor(Math.random()*1000000);document.write('<div id=\"'+arandDiv+'\" style=\"width: 0.001px;height: 0.001px;margin: 0;padding: 0;opacity: 0\"></div>');function isShow(){var itop=document.getElementById(arandDiv).getBoundingClientRect().top;var ise=document.documentElement.clientHeight;if(itop<=ise&&itop>0){return true}else{return false}}");
            out.print("function url(){return encodeURIComponent(win.location.href)}function getScreenResolution(){return win.screen.width+\"*\"+win.screen.height}var coord;function getMousePos(event){var e=event||win.event;var scrollX=doc.documentElement.scrollLeft||doc.body.scrollLeft;var scrollY=doc.documentElement.scrollTop||doc.body.scrollTop;var x=e.pageX||e.clientX+scrollX;var y=e.pageY||e.clientY+scrollY;return{'x':x,'y':y}}doc.getElementsByTagName('body')[0].addEventListener('click',function(){coord=getMousePos(event);console.log('点击坐标：'+coord.x+',,,'+coord.y)});");
            out.print("function GPU(){var canvas=doc.createElement('canvas'),gl=canvas.getContext('experimental-webgl'),debugInfo=gl.getExtension('WEBGL_debug_renderer_info');return gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL)}function title(){return doc.title}function phoneInformation(){var phoneInformation;Array.prototype.contains=function(needle){for(i in this){if(this[i].indexOf(needle)>0)return i}return-1};var device_type=navigator.userAgent;doc.write(device_type);var md=new MobileDetect(device_type);var os=md.os();var model=\"\";if(os==\"iOS\"){os=md.os()+md.version(\"iPhone\");model=md.mobile()}else if(os==\"AndroidOS\"){os=md.os()+md.version(\"Android\");var sss=device_type.split(\";\");var i=sss.contains(\"Build/\");if(i>-1){model=sss[i].substring(0,sss[i].indexOf(\"Build/\"))}}phoneInformation={browserName:md.userAgents(),phoneSystem:os,phoneModel:model,};return phoneInformation}");
            out.print("function uuid(len,radix){var chars='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');var uuid=[],i;radix=radix||chars.length;if(len){for(i=0;i<len;i++)uuid[i]=chars[0|Math.random()*radix]}else{var r;uuid[8]=uuid[13]=uuid[18]=uuid[23]='-';uuid[14]='4';for(i=0;i<36;i++){if(!uuid[i]){r=0|Math.random()*16;uuid[i]=chars[(i==19)?(r&0x3)|0x8:r]}}}return uuid.join('')}var uuid=uuid(8,10);if(!cookie.get('UUID_XB')){cookie.addCookie('UUID_XB',uuid,Infinity)}console.log('uuid:'+uuid);");
            out.print("function searchInformation(){var referrer,searchInformation;try{referrer=win.opener?win.opener.doc.location.href:doc.referrer}catch(e){referrer=doc.referrer}referrer='https://www.google.com.hk/search?safe=strict&source=hp&ei=m9w-W7PKFsa10gTTgKroCw&q=js+%E5%88%A4%E6%96%AD%E6%90%9C%E7%B4%A2%E5%BC%95%E6%93%8E&oq=js+%E5%88%A4%E6%96%AD%E6%90%9C%E7%B4%A2%E5%BC%95%E6%93%8E&gs_l=psy-ab.3...807.807.0.1855.1.1.0.0.0.0.174.174.0j1.1.0....0...1c.1.64.psy-ab..0.0.0....0.RIf1uvH9ETY';function content(r){var s=[\"wd\",\"p\",\"q\",\"keyword\",\"kw\",\"w\",\"key\",\"word\",\"query\",\"q1\",\"name\"];if(r!=\"\"&&r!=null){for(var i=0;i<s.length;i++){var re=new RegExp(\"[^1-9a-zA-Z]\"+s[i]+\"=\\([^&]*\\)\");var kk=r.match(re);if(kk!=null){return kk[1]}}}return\"\"}function engine(r){var regexp=/\\.(sogou|soso|baidu|google|youdao|yahoo|bing|118114|biso|gougou|ifeng|ivc|sooule|niuhu|biso)(\\.[a-z0-9\\-]+){1,2}\\//ig;if(r!=\"\"&&r!=null){return r.match(regexp)}return\"\"}searchInformation=referrer?{referrer:encodeURIComponent(referrer),content:encodeURIComponent(content(referrer)),engine:encodeURIComponent(engine(referrer))}:{referrer:encodeURIComponent(referrer)};return searchInformation}");
            out.print("function isWeiXin(){var ua=window.navigator.userAgent.toLowerCase();if(ua.match(/MicroMessenger/i)=='micromessenger'){return'MicroMessenger'}else{return false}}var userAgent=window.navigator.userAgent;var isShow=isShow(),url=url(),screen=getScreenResolution(),GPU=GPU(),title=title(),isWeiXin=isWeiXin(),browserName=browserName(),phoneInformation=phoneInformation(),searchInformation=searchInformation();function __imgGet(){var __imgXb=new Image();__imgXb.src=\"?lm_id=\"+lm_id+\"&site_id=\"+site_id+\"&userAgent=\"+userAgent+\"&referrer=\"+searchInformation.referrer+\"&url=\"+url+\"&screen=\"+screen+\"&GPU=\"+GPU+\"&title=\"+title+\"&content=\"+searchInformation.content+\"&engine=\"+searchInformation.engine+\"&uuid=\"+cookie.get('UUID_XB')+\"&isWeiXin=\"+isWeiXin;console.log(__imgXb.src)}__imgGet()})();");

        } catch (IOException e) {
        }



    }

}
